#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__author__ = "Administrator"
__name__="servialize"
__date__="2016/8/12"
__time__="16:59"
"""
import global_settings
import pickle,time
from conf.hosts import monitored_groups
# windows下有问题
from redishelper import RedisHelper

# 根据客户的IP获取配置信息
def config_serializer(client_ip):
    applied_services = []
    configs = {
        'services-hehe':{},# 放到service-hehe字典下，用于扩展，比如发布其他消息，或传送文件，根据这一级字典名称可以判断传送的消息是什么类别：监控类、数据采集、传送文件等等
    }
    for group in monitored_groups:  # 取出所有组
        if client_ip in group.hosts:    # 判断client_ip是在组中
            applied_services.extend(group.services) # group是templates.LinuxTemplate的实例，有services动态字段。
    applied_services = set(applied_services)    # 列表去重。
    print applied_services  # 此处的服务是类


    for service in applied_services:    # 循环服务
        ser = service() # 将服务实例化，cpu，memory等服务的实例
        configs['services-hehe'][ser.name] = [ser.interval,
                                             ser.plugin_name,
                                              0 # 最后检测时间
                                             ]  # 嵌套字典，services-hehe的值是字典，ser.name是键，值是一个列表，例如： {'aaa': {'b': [1, 2, 3], 'c': [4, 5.6]}}
    return configs
def flush_all_host_configs_into_redis():    # 将客户端所有需要配置信息存到redis中，供客户端来取。
    applied_hosts=[]
    redis_cli = RedisHelper()   # 实例化，
    for group in monitored_groups:
        applied_hosts.extend(group.hosts)
    applied_hosts=set(applied_hosts)    # 将所有主机ip放入一个列表
    for host_ip in applied_hosts:
        host_config = config_serializer(host_ip)    # 每个ip的配置信息
        key = 'HostConfig::%s' % host_ip
        redis_cli.set(key,pickle.dumps(host_config))  # 调用set方法，将IP:CONFIG,存入redis
    return True
def report_service_data(server_instance,msg):
    host_ip = msg['ip']
    service_status_data = mag['data']
    service_name = msg['service_name']
    server_instance.hosts['hosts'][host_ip][service_name] = {
        'data':service_status_data,
        'time_stamp':time.time()
    }   # 加上时间戳
    key = 'StatusData::%s' % host_ip
    server_instance.redis.set(key,pickle.dumps(server_instance.hosts['hosts'][host_ip]))

def all_host_configs():
    configs = {'hosts':{}}
    for group in monitored_groups:
        for host_ip in group.hosts:
            configs['hosts'][host_ip] = {}
if __name__ =='__main__':
    #config_serializer('192.168.1.1')
    flush_all_host_configs_into_redis()
